<?php
// 假设一开始用的是CsvOrderRepository, 随着订单增加，需要记录日志到DatabaseOrderRepository, 此时需要替换.

interface OrderValidatorInterface{
	public function logOrder(Order $order){}
}

class DatabaseOrderRepositoryError implements OrderValidatorInterface {
	protected $connection;

	public function connect($username, $password)
	{
		$his->connection = new DatabaseConnection($username, $password);
	}

	public function logOrder(Order $order)
	{
		// code...
		$this->connection->run("insert into orders value(?, ?)", array($order->id, $order->amount));
	}
}


class OrderProcessor {
	public function process(Order $order)
	{
		// 需要在调用的地方判断，违背了里氏替换原则。
		if ($this->repository instalceof DatabaseOrderRepositoryError) {
			$this->repository->connect('root', 'password');
		}
		// ... validate order and bill
		$this->orders->logOrder($order);
	}
}


// =========== 优化后的 =================
class DatabaseOrderRepository implements OrderValidatorInterface{
	protected $connector;

	public function __construct(DatabaseConnection $connector)
	{
		$this->connector = $connector;
	}

	public function connect()
	{
		return $this->connector->bootConnection();
	}

	public function logOrder(Order $order)
	{
		$connection = $this->connect();
		$connection->run("insert into orders value(?, ?)", array($order->id, $order->amount));
	}
}


//  调用地方
class OrderProcessor2 {
	public function process(Order $order)
	{
		// ... validate order and bill
		$this->orders->logOrder($order);
	}
}

// 实例化的地方，直接实例化DatabaseOrderRepository即可